function varargout = run_recognition(varargin)
%  __  __                            _   _       
% |  \/  |                          | | | |      
% | \  / | __ _ _ __ __ _ _   _  ___| |_| |_ ___ 
% | |\/| |/ _` | '__/ _` | | | |/ _ \ __| __/ _ \
% | |  | | (_| | | | (_| | |_| |  __/ |_| ||  __/
% |_|  |_|\__,_|_|  \__, |\__,_|\___|\__|\__\___|
%                      | |                       
%                      |_|                       
%  _    _       _                    _ _         
% | |  | |     (_)                  (_) |        
% | |  | |_ __  ___   _____ _ __ ___ _| |_ _   _ 
% | |  | | '_ \| \ \ / / _ \ '__/ __| | __| | | |
% | |__| | | | | |\ V /  __/ |  \__ \ | |_| |_| |
%  \____/|_| |_|_| \_/ \___|_|  |___/_|\__|\__, |
%                                           __/ |
%                                          |___/ 
% 
% Last Modified by Corey Bost for Marquette University's
% Speech and Signal Processing Lab

%This file is part of the Marquette Univeristy Speech Recognition Toolkit.
%
%This module can be used if you have completed training on some data set
%and have other sound files you beleive fit into the categories you
%assigned. When run with the files it asks for, the HTK tools will generate
%a text file telling the user the name of each file used for testing, and
%the category it beleives the sound belongs to. The user should only take
%these results to be an estimate, not definitive.

% RUN_RECOGNITION M-file for run_recognition.fig
%      RUN_RECOGNITION, by itself, creates a new RUN_RECOGNITION or raises the existing
%      singleton*.
%
%      H = RUN_RECOGNITION returns the handle to a new RUN_RECOGNITION or the handle to
%      the existing singleton*.
%
%      RUN_RECOGNITION('CALLBACK',hObject,eventData,handles,...) calls the local
%      function named CALLBACK in RUN_RECOGNITION.M with the given input arguments.
%
%      RUN_RECOGNITION('Property','Value',...) creates a new RUN_RECOGNITION or raises the
%      existing singleton*.  Starting from the left, property value pairs are
%      applied to the GUI before run_recognition_OpeningFcn gets called.  An
%      unrecognized property name or invalid value makes property application
%      stop.  All inputs are passed to run_recognition_OpeningFcn via varargin.
%
%      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
%      instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help_menu run_recognition

% Last Modified by GUIDE v2.5 06-Aug-2009 10:44:30

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @run_recognition_OpeningFcn, ...
                   'gui_OutputFcn',  @run_recognition_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT

% --- Executes just before run_recognition is made visible.
function run_recognition_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to run_recognition (see VARARGIN)

% Choose default command line output for run_recognition
handles.output = hObject;
global main_dir; 
if isnumeric(main_dir), main_dir = strrep(which('run_recognition_OpeningFcn'),'\run_recognition.m','');end
global info;
info = [];
global flag;
flag = [0,0,0,0,0,0,0];
% Update handles structure
guidata(hObject, handles);
set(gcf,'CloseRequestFcn',@my_closefcn);

% UIWAIT makes run_recognition wait for user response (see UIRESUME)
% uiwait(handles.figure1);

%User defined close function
function my_closefcn(hObject, eventdata, handles, varargin)
global main_dir;
cd(main_dir);
delete(gcf);
htk_tools

% --- Outputs from this function are returned to the command line.
function varargout = run_recognition_OutputFcn(hObject, eventdata, handles) 
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;


% --- Executes on selection change in listbox1.
function listbox1_Callback(hObject, eventdata, handles)
% hObject    handle to listbox1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = get(hObject,'String') returns listbox1 contents as cell array
%        contents{get(hObject,'Value')} returns selected item from listbox1


% --- Executes during object creation, after setting all properties.
function listbox1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to listbox1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: listbox controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end

% --- Executes on button press in browse.
function browse_Callback(hObject, eventdata, handles)
% hObject    handle to browse (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

%This begins the selection for which type of directory dialog needs to be
%opened depending on the drop down menu. The case statement is evalutaed
%based on that drop down.
global info;
global main_dir;
global flag;
val = get(handles.popup, 'value');
switch val
    case 1
        if flag(val) == 0
            info{val} = ' ';
            [new, test, name_check] = need_file(hObject, eventdata, handles, val);
            flag(val) = 1;
        else 
            [new, test, name_check] = need_file(hObject, eventdata, handles, val);
        end
        if test ~= 0
            if strcmp(name_check, 'hmmdefs')
                info{val} = new{1};
                load_listbox(hObject, eventdata, handles, info);
            else
                errordlg('Please select a valid HMM definition file.');
            end
        end
    case 2
        if flag(val) == 0
            info{val} = ' ';
            [new, test] = need_dir(hObject, eventdata, handles);
            flag(val) = 1;
        else 
            [new, test] = need_dir(hObject, eventdata, handles);
        end
        if test ~= 0
            info{val} = new{1};
            load_listbox(hObject, eventdata, handles, info);
        end
    case 3
        if flag(val) == 0
            info{val} = ' ';
            [new, test, name_check] = need_file(hObject, eventdata, handles, val);
            flag(val) = 1;
        else 
            [new, test, name_check] = need_file(hObject, eventdata, handles, val);
        end
        if test ~= 0
            if strcmp(name_check, 'config')
                info{val} = new{1};
                load_listbox(hObject, eventdata, handles, info);
            else
                errordlg('Please select a valid configuration file.');
            end
        end
    case 4
        if flag(val) == 0
            info{val} = ' ';
            [new, test, name_check] = need_file(hObject, eventdata, handles, val);
            flag(val) = 1;
        else 
            [new, test, name_check] = need_file(hObject, eventdata, handles, val);
        end
        if test ~= 0
            if strcmp(name_check, 'wdnet')
                info{val} = new{1};
                load_listbox(hObject, eventdata, handles, info);
            else
                errordlg('Please select a valid WDNET file.');
            end
        end
    case 5
        if flag(val) == 0
            info{val} = ' ';
            [new, test, name_check] = need_file(hObject, eventdata, handles, val);
            flag(val) = 1;
        else 
            [new, test, name_check] = need_file(hObject, eventdata, handles, val);
        end
        if test ~= 0
            if strcmp(name_check, 'gram')
                info{val} = new{1};
                load_listbox(hObject, eventdata, handles, info);
            else
                errordlg('Please select a valid grammar file.');
            end
        end
    case 6
        if flag(val) == 0
            info{val} = ' ';
            [new, test, name_check] = need_file(hObject, eventdata, handles, val);
            flag(val) = 1;
        else 
            [new, test, name_check] = need_file(hObject, eventdata, handles, val);
        end
        if test ~= 0
            if strcmp(name_check, 'dict')
                info{val} = new{1};
                load_listbox(hObject, eventdata, handles, info);
            else
                errordlg('Please select a valid dictionary file');
            end
        end
    case 7
        if flag(val) == 0
            info{val} = ' ';
            [new, test, name_check] = need_file(hObject, eventdata, handles, val);
            flag(val) = 1;
        else
            [new, test, name_check] = need_file(hObject, eventdata, handles, val);
        end
        if test ~= 0
            if strcmp(name_check, 'model.list')
                info{val} = new{1};
                load_listbox(hObject, eventdata, handles, info);
            else
                errordlg('Please select a valid model.list file');
            end
        end
end
check_run(hObject, eventdata, handles);



% --- Executes on button press in delete.
function delete_Callback(hObject, eventdata, handles)
% hObject    handle to delete (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global info;
%This delets the selected item in the listbox and from the variablo "info"
%to keep track of everything.
selection = get(handles.listbox1,'value');
location = cellstr(get(handles.listbox1,'string'));
str1 = location(selection);
for i=1:length(info)
    TF = strcmp(str1,info(i));
    if TF == 1
        info{i} = '';
        set(handles.recognition,'enable','off');
    end
end
location(selection) = [];
if isempty(location)
    set(handles.delete,'enable','off');
    set(handles.recognition,'enable','off');
    selection = 1;
end
selection = min(selection,length(location));
set(handles.listbox1, 'value', 1, 'string', location);


% --- Executes on selection change in popup.
function popup_Callback(hObject, eventdata, handles)
% hObject    handle to popup (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = get(hObject,'String') returns popup contents as cell array
%        contents{get(hObject,'Value')} returns selected item from popup


% --- Executes during object creation, after setting all properties.
function popup_CreateFcn(hObject, eventdata, handles)
% hObject    handle to popup (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: popupmenu controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in recognition.
function recognition_Callback(hObject, eventdata, handles)
% hObject    handle to recognition (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
global info;
h= msgbox('Please wait while we identify your data...','Looking at data');
flag = test_for_rec(info{2});
if ~flag
%     if exist(h,'var')==1, delete(h);end
    errordlg('The chosen data directory contains invalid files.');
    return
end
[input_name,output_label] = run_labeling(info);
msgbox('Your data has been evaluated.','Complete');
fid = fopen('Data/recognition_results.txt','w');
for i=1:length(output_label)
    fprintf(fid,['File ' input_name{i} '\t was recognized as \t' output_label{i} '\n']);
end
fclose(fid);
winopen('data/recognition_results.txt');

function [new, pathname, name_check] = need_file(hObject, eventdata, handles, val)
% hObject    handle to recognition (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

location = get(handles.listbox1, 'string');
[new,pathname,filterindex] = uigetfile('*.*');
name_check = new;
new = [pathname '' new];
if new ~=0
    new = cellstr(new);
    if ~isempty(new) & ~(strcmp(new,' '))
        if isempty(location)
            location = new;
        else
            location(end+1) = new;
        end
        if val == 1
            if strcmp(name_check, 'hmmdefs')
                load_listbox(hObject, eventdata, handles, location);
            end
        elseif val == 3
            if strcmp(name_check, 'config')
                load_listbox(hObject, eventdata, handles, location);
            end
        elseif val == 4
            if strcmp(name_check, 'wdnet')
                load_listbox(hObject, eventdata, handles, location);
            end
        elseif val == 5
            if strcmp(name_check, 'gram')
                load_listbox(hObject, eventdata, handles, location);
            end
        elseif val == 6
            if strcmp(name_check, 'dict')
                load_listbox(hObject, eventdata, handles, location);
            end
        elseif val == 7
            if strcmp(name_check, 'model.list')
                load_listbox(hObject, eventdata, handles, location);
            end
        end
    end
end

function [new, test] = need_dir(hObject, eventdata, handles)
% hObject    handle to recognition (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
test = 0;
location = get(handles.listbox1, 'string');
new = uigetdir('*.*');
if new ~= 0
    new = cellstr(new);
    test=1;
    if ~isempty(new) & ~(strcmp(new,' '))
        if isempty(location)
            location = new;
        else
            location(end+1) = new;
        end
        load_listbox(hObject, eventdata, handles, location);
    end
end

function load_listbox(hObject, eventdata, handles, location)
% hObject    handle to recognition (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)location = sortrows(location);
global info;
val = get(handles.popup, 'value');
if ~strcmpi(info{val},' ')
    set(handles.listbox1,'string',location)
    set(handles.delete,'enable', 'on');
end
if strcmpi(info{val},' ')
    set(handles.listbox1,'string',info)
end

function check_run(hObject, eventdata, handles)
flagy = 0;
global info;
global flag;
test = 0;
%this loop checks to see that all values have been set at least once
for i=1:length(flag)
    if flag(i) == 0
        flagy = 1;
    end
end
%This second loop checks to see that all values are still associated with a
%file.
if length(info)==length(get(handles.popup,'string'))
    for i=1:length(info)
       if ~strcmpi(info{i},'') & flagy ==0
            set(handles.recognition,'enable','on');
       else
           set(handles.recognition,'enable','off');
           test = 1;
       end
    end
end
if test == 1
     set(handles.recognition,'enable','off');
end


% --------------------------------------------------------------------
function help_menu_Callback(hObject, eventdata, handles)
% hObject    handle to help_menu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)


% --------------------------------------------------------------------
function help_Callback(hObject, eventdata, handles)
% hObject    handle to help (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
%{
helpdlg(sprintf(['Select an item from the dropdown menu.\n\n'...
    'Click "Browse" and then choose the appropriate file or directory '...
    'corresponding to the selected item in the dropdown menu.\n\n'...
    'Repeat this process for every other item in the dropdown menu.\n\n'...
    'If you make a mistake and select the wrong file, simply click the '...
    'file in the list box, and then click the delete button.\n\n'...
    'Once this is done, click the "Run Recognition" button and a text '...
    'file will be saved and opened showing the results of the test.']));
%}
help_launch('runrec');

% --------------------------------------------------------------------
function about_us_Callback(hObject, eventdata, handles)
% hObject    handle to about_us (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
about_us;

% --------------------------------------------------------------------
function exit_Callback(hObject, eventdata, handles)
% hObject    handle to exit (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
my_closefcn(hObject,eventdata,handles);


% --------------------------------------------------------------------
function file_menu_Callback(hObject, eventdata, handles)
% hObject    handle to file_menu (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
